package org.example.commons.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import org.example.commons.constant.Constants;
import org.springframework.web.client.RestTemplate;

/**
 * @author bothin
 */
public class WeiXinUtils {
    public static final RestTemplate REST_TEMPLATE = new RestTemplate();

    /**
     * {"session_key":"XYnH3hLrUriMZqufAKhqug==","openid":"oyMxL5HQIlHbqJ72qUNyD55Ltqx8"}
     * @param code
     * @param appId
     * @param appSecret
     * @return
     */
    public static String getOpenid(String code, String appId, String appSecret){
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + appId
                + "&secret=" + appSecret
                + "&js_code=" + code
                + "&grant_type=authorization_code";
        return REST_TEMPLATE.getForObject(url, String.class);
    }

    /**
     * 返回真正的openid
     * @param code
     * @param appId
     * @param appSecret
     * @return openid
     * @throws JsonProcessingException
     */
    public static String getRealOpenid(String code, String appId, String appSecret) throws JsonProcessingException {
        String json = getOpenid(code,appId,appSecret);
        JsonNode jsonNode = Constants.MAPPER.readTree(json);
        return jsonNode.get("openid").asText();
    }
}
